//
//  CNOrderDetailTableViewController.m
//  BeeQuick_19
//
//  Created by 赵玉忠 on 16/9/24.
//  Copyright © 2016年 CN Team. All rights reserved.
//

#import "CNOrderDetailTableViewController.h"
#import "UIBarButtonItem+CNAddNewAddressUIBarButtonItem.h"
#import "CNOrderStatasTableViewCell.h"
#import "CNOrderStatasModel.h"
#import "CNRightFirstSectionTableViewCell.h"
#import "CNRightTwoSectionTableViewCell.h"
#import "CNFourSectionLastTableViewCell.h"
#import "CNThreeSectionLastTableViewCell.h"
#import "CNThreeSectionFirstCell.h"
@interface CNOrderDetailTableViewController ()
@property (nonatomic,weak) UIButton *leftButton;
@property (nonatomic,weak) UIButton *rightButton;
@property (nonatomic,weak) UILabel *leftLabel;
@property (nonatomic,weak) UILabel *rightLabel;
@property (nonatomic,assign) BOOL leftTag;

@property (nonatomic,weak) UIView *bottomButtonView;

@property (nonatomic,strong) NSArray *orderStatasModelArray;

@property (nonatomic,strong) NSArray *ThreeSectionArray;

@property (nonatomic,copy) NSString *count;

@end

static NSString *CNOrderStatasTableViewCellID = @"CNOrderStatasTableViewCellID";
static NSString *RightFirstSectionCellID = @"RightFirstSectionCellID";
static NSString *CNRightFirstSectionTableViewCellID = @"CNRightFirstSectionTableViewCellID";
static NSString *CNRightTwoSectionTableViewCellID = @"CNRightTwoSectionTableViewCellID";
static NSString *CNFourSectionLastTableViewCellID = @"CNFourSectionLastTableViewCellID";
static NSString *CNThreeSectionLastTableViewCellID = @"CNThreeSectionLastTableViewCellID";
static NSString *CNThreeSectionFirstCellID = @"CNThreeSectionFirstCellID";

@implementation CNOrderDetailTableViewController

#pragma mark - 将要出现
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 60, 0);
    
    //往窗口添加视图
    [self loadButtonView];

    if (self.leftTag == YES) {
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }else{
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    }

}

#pragma mark - 将要消失
-(void)viewWillDisappear:(BOOL)animated{
    [self.bottomButtonView removeFromSuperview];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadData];
    
    //加载订单状态页面
    self.orderStatasModelArray = [self loadDataWith:@"OrderStatas.plist" ToModel:[CNOrderStatasModel class]];
    NSLog(@"%ld",self.orderStatasModelArray.count);
    //titleView
    
    UIBarButtonItem *item =  [[UIBarButtonItem alloc]initWithImage:nil style:UIBarButtonItemStylePlain target:self action:@selector(click)];
    item.title = @"在线客服";
    item.tintColor = [UIColor colorWithWhite:0.5 alpha:1];
    self.navigationItem.rightBarButtonItem = item;

//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:lineButton];
    
    
    NSArray *segmentedArray = [[NSArray alloc]initWithObjects:@"订单状态",@"订单详情",nil];
    //初始化UISegmentedControl
    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]initWithItems:segmentedArray];
//    segmentedControl.tintColor = [UIColor colorWithRed:252/255.0 green:211/255.0 blue:52/255.0 alpha:1];
    segmentedControl.tintColor = [UIColor whiteColor];
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor darkGrayColor],NSForegroundColorAttributeName,nil];
    [segmentedControl setTitleTextAttributes:dic forState:UIControlStateSelected];
    NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor lightGrayColor],NSForegroundColorAttributeName,nil];
    [segmentedControl setTitleTextAttributes:dic1 forState:UIControlStateNormal];

    [segmentedControl setWidth:90.0 forSegmentAtIndex:0];
    [segmentedControl setWidth:90.0 forSegmentAtIndex:1];
    [segmentedControl addTarget:self action:@selector(changeView:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = segmentedControl;
    
    //添加返回按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"v2_goback"] forState:UIControlStateNormal];
    // 可以设置成图像的大小
    //当设置了按钮的image属性之后, 那么currentImage就会有值
    button.size = button.currentImage.size;
    [button addTarget:self action:@selector(backClick) forControlEvents: UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem =  [[UIBarButtonItem alloc] initWithCustomView:button];

    
    //加载nib Cell
    [self loadNibCell];
    
    [self leftButtonClick];
    segmentedControl.selectedSegmentIndex = 0;
    
}

-(void)backClick{
    UINavigationController *nv = self.navigationController;
    NSInteger cout = self.navigationController.viewControllers.count;
    for (int i=0; i<3; i++) {
        UIViewController *vc = nv.viewControllers[cout-1-i];
        [vc.navigationController popViewControllerAnimated:NO];
    }
}

-(void)changeView:(UISegmentedControl *)seg{
    NSInteger index = seg.selectedSegmentIndex;
    if (index == 0) {
            [self leftButtonClick];
    }else{
            [self rightButtonClick];
    }
}

#pragma mark - 在线客服按钮的点击
-(void)click{
    
}

#pragma 左边按钮的点击
-(void)leftButtonClick{
    self.leftTag = YES;
    self.leftButton.selected = YES;
    self.rightButton.selected = NO;

    [self.tableView reloadData];
}
#pragma 右边按钮的点击
-(void)rightButtonClick{
    self.leftTag = NO;
    self.rightButton.selected = YES;
    self.leftButton.selected = NO;
    [self.tableView reloadData];
}
#pragma mark - 加载nib
-(void)loadNibCell{
    [self.tableView registerNib:[UINib nibWithNibName:@"CNOrderStatasTableViewCell" bundle:nil] forCellReuseIdentifier:CNOrderStatasTableViewCellID];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:RightFirstSectionCellID];
    [self.tableView registerNib:[UINib nibWithNibName:@"CNRightFirstSectionTableViewCell" bundle:nil] forCellReuseIdentifier:CNRightFirstSectionTableViewCellID];
    [self.tableView registerNib:[UINib nibWithNibName:@"CNRightTwoSectionTableViewCell" bundle:nil] forCellReuseIdentifier:CNRightTwoSectionTableViewCellID];
    [self.tableView registerNib:[UINib nibWithNibName:@"CNFourSectionLastTableViewCell" bundle:nil] forCellReuseIdentifier:CNFourSectionLastTableViewCellID];
    [self.tableView registerNib:[UINib nibWithNibName:@"CNThreeSectionLastTableViewCell" bundle:nil] forCellReuseIdentifier:CNThreeSectionLastTableViewCellID];
    [self.tableView registerNib:[UINib nibWithNibName:@"CNThreeSectionFirstCell" bundle:nil] forCellReuseIdentifier:CNThreeSectionFirstCellID];
}
#pragma mark -返回按钮的点击
-(void)backButtonClick{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -加载数据
-(NSArray *)loadDataWith:(NSString *)plistPath ToModel:(Class)Model{
    NSArray *plistArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle]pathForResource:plistPath ofType:nil]];
    NSArray *modelArray = [NSArray yy_modelArrayWithClass:Model json:plistArray];
    return modelArray;
}


#pragma mark - tableView DataSouce
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.leftTag == YES) {
        return 1;
    }else{
        return 3;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.leftTag == YES) {
        return self.orderStatasModelArray.count;
    }else{
        NSInteger rowsInSection;
        rowsInSection = [self rowsInSection:section];
        return rowsInSection;
    }
}

//右边每组行数
-(NSInteger)rowsInSection:(NSInteger)section{
    if (section == 2) {
        return self.ThreeSectionArray.count + 3;
    }else{
        return 1;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.leftTag == YES) {
        CNOrderStatasTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CNOrderStatasTableViewCellID forIndexPath:indexPath];
        CNOrderStatasModel *model = self.orderStatasModelArray[indexPath.row];
        cell.model = model;
        if (indexPath.row == 0) {
            [cell dealWithFirstCell];
        }
        if (indexPath.row == (self.orderStatasModelArray.count - 1)) {
            [cell dealWithLastCell];
        }
        return cell;
    }else{
        UITableViewCell *cell ;
        cell = [self loadRightCell:indexPath andTableView:tableView];
//        if (indexPath.section == 2 && indexPath.row == 3) {
//            CGFloat maxY = CGRectGetMaxY(cell.frame);
//            self.tableView.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, maxY+10)
//        }

        return cell;
    }
}
#pragma mark - 右边显示cell 
-(UITableViewCell *)loadRightCell:(NSIndexPath *)indexpath andTableView:(UITableView *)tableView{
    if (indexpath.section == 0) {
        CNRightFirstSectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CNRightFirstSectionTableViewCellID forIndexPath:indexpath];
        return cell;
    }else if (indexpath.section == 1){
        CNRightTwoSectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CNRightTwoSectionTableViewCellID forIndexPath:indexpath];
        return cell;
    }else{
        if (indexpath.row == 0) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RightFirstSectionCellID forIndexPath:indexpath];
            cell.textLabel.text = @"费用明细";
            cell.textLabel.textColor = [UIColor lightGrayColor];
            cell.textLabel.font = [UIFont systemFontOfSize:15];
            return cell;
        }else if (indexpath.row == self.ThreeSectionArray.count + 1){
            CNFourSectionLastTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CNFourSectionLastTableViewCellID forIndexPath:indexpath];
            
                        CGFloat count = 0.0;
                        for (CNGoodsModel *model in self.ThreeSectionArray) {
                            count += model.count * model.partner_price;
                        }
                        cell.amount = [NSString stringWithFormat:@"%.2f",count];
                        self.count = cell.amount;
            

            return cell;
        }else if(indexpath.row == self.ThreeSectionArray.count + 2){
            CNThreeSectionLastTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CNThreeSectionLastTableViewCellID forIndexPath:indexpath];
            cell.name = @"实付：";
            cell.count = self.count;
            cell.color = [UIColor redColor];
            

            
            return cell;
        }else{
            CNThreeSectionFirstCell *cell = [tableView dequeueReusableCellWithIdentifier:CNThreeSectionFirstCellID forIndexPath:indexpath];
            cell.model = self.ThreeSectionArray[indexpath.row-1];
            return cell;
        }

    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.leftTag == YES) {
        return 90;
    }else{
        if (indexPath.section == 0) {
            return 200;
        }else if(indexPath.section == 1){
            return 100;
        }else if(indexPath.section == 2 && indexPath.row == 0){
            return 50;
        }else if(indexPath.section == 2 && indexPath.row == self.ThreeSectionArray.count +1){
            return 130;
        }else if(indexPath.section == 2 && indexPath.row == self.ThreeSectionArray.count +2){
            return 50;
        }else{
            return 50;
        }
    }
    
}
#pragma mark - 设置组间距
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0;
    }else{
        return 20;
    }
}
#pragma mark - 往窗口添加视图
-(void)loadButtonView{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *buttomView = [UIView new];
    self.bottomButtonView = buttomView;
    buttomView.backgroundColor = [UIColor whiteColor];
    [window addSubview:buttomView];
    [buttomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(window);
        make.height.offset(60);
    }];
    UIView *lineView = [UIView new];
    lineView.backgroundColor = [UIColor lightGrayColor];
    [buttomView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(buttomView);
        make.height.offset(1);
    }];
    
    //添加三个按钮
    UIButton *goPayButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [goPayButton addTarget:self action:@selector(goPayButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [goPayButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
    [goPayButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    goPayButton.layer.cornerRadius = 5;
    goPayButton.backgroundColor = [UIColor colorWithRed:252/255.0 green:211/255.0 blue:52/255.0 alpha:1];
   [goPayButton setTitle:@"去支付" forState:UIControlStateNormal];
    goPayButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [buttomView addSubview:goPayButton];
    [goPayButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(buttomView.mas_right).offset(-10);
        make.centerY.equalTo(buttomView);
        make.width.offset(70);
    }];
    
    UIButton *cancleOrderButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancleOrderButton addTarget:self action:@selector(cancleOrderButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [cancleOrderButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
    [cancleOrderButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    cancleOrderButton.layer.cornerRadius = 5;
    cancleOrderButton.backgroundColor = [UIColor colorWithRed:252/255.0 green:211/255.0 blue:52/255.0 alpha:1];
    [cancleOrderButton setTitle:@"取消订单" forState:UIControlStateNormal];
    cancleOrderButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [buttomView addSubview:cancleOrderButton];
    [cancleOrderButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(goPayButton.mas_left).offset(-10);
        make.centerY.equalTo(buttomView);
        make.width.offset(90);
    }];
    
    UIButton *oneMoreOrderButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [oneMoreOrderButton addTarget:self action:@selector(oneMoreButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [oneMoreOrderButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
    [oneMoreOrderButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    oneMoreOrderButton.layer.cornerRadius = 5;
    oneMoreOrderButton.backgroundColor = [UIColor colorWithRed:252/255.0 green:211/255.0 blue:52/255.0 alpha:1];
    [oneMoreOrderButton setTitle:@"再来一单" forState:UIControlStateNormal];
    oneMoreOrderButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [buttomView addSubview:oneMoreOrderButton];
    [oneMoreOrderButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(cancleOrderButton.mas_left).offset(-10);
        make.centerY.equalTo(buttomView);
        make.width.offset(90);
    }];
}
#pragma mark -底部三个按钮的点击
//去支付按钮的点击
-(void)goPayButtonClick{
    NSLog(@"点击了去支付按钮");
    [self.navigationController popViewControllerAnimated:YES];
}
//取消订单按钮的点击
-(void)cancleOrderButtonClick{
    NSLog(@"点击了去取消订单按钮");
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"警告" message:@"你的操作将取消订单，您要继续吗" preferredStyle:UIAlertControllerStyleAlert];
    
    // 添加按钮
    __weak typeof(alert) weakAlert = alert;
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        [self backToRootViewController];
        NSLog(@"点击了确定按钮--%@-%@", [weakAlert.textFields.firstObject text], [weakAlert.textFields.lastObject text]);
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        NSLog(@"点击了取消按钮");
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
    
}
//再来一单按钮的点击
-(void)oneMoreButtonClick{
    NSLog(@"点击了再来一单按钮");
    [self backToRootViewController];
}

#pragma mark - 回到根控制器的方法
- (void)backToRootViewController{
    UINavigationController *nv = self.navigationController;
    NSInteger cout = self.navigationController.viewControllers.count;
    for (int i=0; i<cout; i++) {
        UIViewController *vc = nv.viewControllers[cout-1-i];
        [vc.navigationController popViewControllerAnimated:NO];
    }

//    UIViewController* vc = [MainViewController instance].navigationController.visibleViewController;
//    if ([vc isEqual:[MainViewController instance]]) return;
//    if (vc.presentingViewController) {
//        [vc dismissViewControllerAnimated:NO completion:^{
//            [self backToRootViewController];
//        }];
//    }
//    else{
//        [vc.navigationController popViewControllerAnimated:NO];
//        [self backToRootViewController];
//    }
}

-(void)loadData{
    NSArray *array = [[SQLiteManager sharedSQLiteManager]queryContact];
    self.ThreeSectionArray = array;
    NSLog(@"%ld",array.count);
}

@end
